package top.zackyoung.thirdlogin.controller;

import com.alibaba.fastjson.JSON;
import com.xkcoding.justauth.AuthRequestFactory;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ZackYoung
 * @version 1.0
 * @description 使用第三方工具justauth
 * @date 2021/6/6 9:18
 */
@RestController
@Slf4j
@RequestMapping("/oauth")
public class LoginTwoController {
    @Resource
    private AuthRequestFactory factory;

    /**
     * 登录
     *
     * @param type     第三方系统类型，例如：gitee/baidu
     * @param response resp
     * @throws IOException 异常
     */
    @GetMapping("/login/{type}")
    public void login(@PathVariable String type, HttpServletResponse response) throws IOException {
        AuthRequest authRequest = factory.get(type);
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }

    /**
     * 登录回调
     *
     * @param type     第三方系统类型，例如：gitee/baidu
     * @param callback 回调
     * @return 登录用户实体
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/{type}/callback")
    public AuthUser login(@PathVariable String type, AuthCallback callback) {
        AuthRequest authRequest = factory.get(type);
        AuthResponse<AuthUser> response = authRequest.login(callback);
        log.info("【response】= {}", JSON.toJSONString(response));
        return response.getData();
    }
}
